<template>
  <div>
    <!-- 添加或修改药品字典基本信息对话框 -->
    <el-dialog v-model="open" :close-on-click-modal="false" append-to-body width="90%">
      <template #header>
        <div style="cursor: move">
          <span style="font-size: 16px; color: #ff8c00"> 温馨提示</span>： 如：<span
          style="color: #ff8c00">厄贝沙坦氢氯噻嗪片</span>，
          说明书上的规格(包装规格)：<span style="color: #ff8c00">0.15g:12.5mg/28片*盒</span>
          。服药剂量：<span style="color: #ff8c00">12.5mg</span> ，剂量单位：<span
          style="color: #ff8c00">片</span>
          ，最小规格：<span style="color: #ff8c00">0.15g;12.5mg</span> ，包装数量：<span
          style="color: #ff8c00">28</span>
          ，最小单位：<span style="color: #ff8c00">片</span> ，包装单位：<span style="color: #ff8c00">盒</span>
        </div>
      </template>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px"
               style="height: 590px; overflow-y: auto">
        <el-divider content-position="left"><span class="divider-css">▶药品基本信息◀</span></el-divider>
        <el-row>
          <el-col :span="6">
            <el-form-item label="药品分类" prop="drugClass">
              <el-select ref="drugClass" v-model="form.drugClass" v-keyupEnter="{ index: 0, name: 'drugClass' }"
                         clearable
                         default-first-option
                         filterable placeholder="请选择药品分类"
                         style="width: 100%"
                         @change="selectChange($event, 'drug_classification', 'drugClassName')">
                <el-option v-for="dict in dictDataMap['drug_classification']" :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="药品类别" prop="drugType">
              <drug-class :value="form.drugTypeName" style="width: 100%"
                          @org-node-click="drugTypeClick"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="药品名称" prop="drugName">
              <el-input ref="drugName" v-model="form.drugName" v-keyupEnter="{ index: 0, name: 'drugName' }"
                        placeholder="请输入药品名称" @blur="drugNameBlue"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="药品别名" prop="drugNameAlias">
              <el-input ref="drugNameAlias" v-model="form.drugNameAlias" @blur="drugNameAliasBlue"
                        v-keyupEnter="{ index: 0, name: 'drugNameAlias' }"
                        placeholder="请输入药品别名"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="药品编码" prop="drugCode">
              <el-input ref="drugCode" v-model="form.drugCode" v-keyupEnter="{ index: 0, name: 'drugCode' }"
                        placeholder="请输入药品编码"
                        @blur="chargeInput($event, 'drugCode', null, null)"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="药品拼音码" prop="drugInput">
              <el-input ref="drugInput" v-model="form.drugInput" v-keyupEnter="{ index: 0, name: 'drugInput' }"
                        placeholder="请输入药品拼音码"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="药品剂型" prop="drugFrom">
              <el-select ref="drugFrom" v-model="form.drugFrom" v-keyupEnter="{ index: 0, name: 'drugFrom' }"
                         default-first-option
                         filterable
                         placeholder="请选择药品剂型"
                         style="width: 100%"
                         @change="selectChange($event, 'drug_form_dict', 'drugFromName')">
                <el-option v-for="dict in dictDataMap['drug_form_dict']" :key="dict.dictValue"
                           :label="dict.dictLabel"
                           :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" class="firm-name-div">
            <el-form-item label="药品厂商" prop="firmId">
              <div>
                <producer :id="form.firmName" ref="firmName" v-keyupEnter="{ index: 0, name: 'firmName' }"
                          :placeholder="'请选择生产厂商'"
                          :tabindex="'11'"
                          style="width: 87%; float: left; display: inline"
                          @producerChange="producerChange"/>
                <el-tooltip class="item" content="新增生产厂商" effect="dark" placement="top-start">
                  <el-button style="width: 13%" type="primary" @click="addSupplier">
                    <template #icon>
                      <i-ep-plus/>
                    </template>
                  </el-button>
                </el-tooltip>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="服药剂量" prop="dose">
              <el-input ref="dose" v-model="form.dose" v-keyupEnter="{ index: 0, name: 'dose' }"
                        :disabled="form.isExistStock"
                        placeholder="请输入剂量"
                        @input="chargeInput($event, 'dose', null, null)"
                        prop="dose" style="width: 65%"/>
              <el-select ref="doseUnits" v-model="form.doseUnits" v-keyupEnter="{ index: 0, name: 'doseUnits' }"
                         :disabled="form.isExistStock"
                         default-first-option filterable placeholder="剂量单位"
                         prop="doseUnits"
                         style="width: 35%"
                         @change="chargeInput($event, 'doseUnits', 'dose_unit', 'doseUnitsName')">
                <el-option v-for="dict in dictDataMap['dose_unit']" :key="dict.dictValue"
                           :label="dict.dictLabel"
                           :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="最小规格" prop="minSpec">
              <el-input ref="minSpec" v-model="form.minSpec" v-keyupEnter="{ index: 0, name: 'minSpec' }"
                        :disabled="form.isExistStock"
                        placeholder="请输入最小规格"
                        @input="chargeInput($event, 'minSpec', null, null)"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="包装数量">
              <el-input ref="packageNum" v-model="form.packageNum" v-keyupEnter="{ index: 0, name: 'packageNum' }"
                        :disabled="form.isExistStock"
                        placeholder="请输入包装数量" prop="packageNum"
                        style="width: 65%"
                        @input="chargeInput($event, 'packageUnits', null, null)"/>
              <el-select ref="minUnits" v-model="form.minUnits" v-keyupEnter="{ index: 0, name: 'minUnits' }"
                         :disabled="form.isExistStock"
                         default-first-option
                         filterable placeholder="最小单位" prop="minUnits"
                         style="width: 35%"
                         @change="chargeInput($event, 'packageUnits', 'spec_unit', 'minUnitsName')">
                <el-option v-for="dict in dictDataMap['spec_unit']" :key="dict.dictValue"
                           :label="dict.dictLabel"
                           :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="包装规格">
              <el-select ref="packageUnits" v-model="form.packageUnits"
                         v-keyupEnter="{ index: 0, name: 'packageUnits' }"
                         :disabled="form.isExistStock" default-first-option filterable
                         placeholder="包装单位" prop="packageUnits"
                         style="width: 35%"
                         @change="chargeInput($event, 'packageUnits', 'spec_unit', 'packageUnitName')">
                <el-option v-for="dict in dictDataMap['spec_unit']" :key="dict.dictValue"
                           :label="dict.dictLabel"
                           :value="dict.dictValue"></el-option>
              </el-select>
              <el-input ref="packageSpec" v-model="form.packageSpec" v-keyupEnter="{ index: 0, name: 'packageSpec' }"
                        :disabled="form.isExistStock"
                        placeholder="请输入包装规格" prop="packageSpec"
                        @input="chargeInput($event, 'lastPackageSpec', null, null)"
                        style="width: 65%"/>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="自费或医保" prop="zfOrYb">
              <el-radio-group ref="zfOrYb" v-model="form.zfOrYb">
                <el-radio v-for="dict in dictDataMap['is_medical_insurance']" :key="dict.dictValue"
                          :tabindex="'12'"
                          :value="dict.dictValue">{{ dict.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="国家医保名称" prop="countryYbName">
              <el-input ref="countryYbName" v-model="form.countryYbName"
                        v-keyupEnter="{ index: 0, name: 'countryYbName' }"
                        :tabindex="'13'"
                        placeholder="请输入国家医保名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="国家医保编码" prop="countryYbCode">
              <el-input ref="countryYbCode" v-model="form.countryYbCode"
                        v-keyupEnter="{ index: 0, name: 'countryYbCode' }"
                        placeholder="请输入国家医保编码"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否高危" prop="highRisk">
              <el-radio-group v-model="form.highRisk">
                <el-radio v-for="dict in dictDataMap['sys_yes_no']" :key="dict.dictValue"
                          :value="dict.dictValue">{{
                    dict.dictLabel
                  }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left"><span class="divider-css">▶药品其他信息◀</span></el-divider>
        <el-row>
          <el-col :span="6">
            <el-form-item label="毒理分类" prop="toxiProperty">
              <el-select ref="toxiProperty" v-model="form.toxiProperty"
                         v-keyupEnter="{ index: 0, name: 'toxiProperty' }" clearable
                         default-first-option
                         filterable placeholder="请选择毒理分类"
                         style="width: 100%"
                         @change="selectChange($event, 'drug_toxi_property_dict', 'toxiPropertyName')">
                <el-option v-for="dict in dictDataMap['drug_toxi_property_dict']" :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="限制等级" prop="limitClass">
              <el-select ref="limitClass" v-model="form.limitClass" v-keyupEnter="{ index: 0, name: 'limitClass' }"
                         clearable
                         default-first-option
                         filterable placeholder="限制等级"
                         style="width: 100%"
                         @change="selectChange($event, 'limit_class_dict', 'basicDrugTypeName')">
                <el-option v-for="dict in dictDataMap['limit_class_dict']" :key="dict.dictValue"
                           :label="dict.dictLabel"
                           :value="dict.dictValue"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="基本药物类型" prop="basicDrugType">
              <el-select ref="basicDrugType" v-model="form.basicDrugType"
                         v-keyupEnter="{ index: 0, name: 'basicDrugType' }" default-first-option
                         filterable placeholder="请选择基本药物类型"
                         style="width: 100%"
                         @change="selectChange($event, 'basic_drug_type', 'basicDrugTypeName')">
                <el-option v-for="dict in dictDataMap['basic_drug_type']" :key="dict.dictValue"
                           :label="dict.dictLabel"
                           :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="抗菌药物">
              <el-radio-group v-model="form.antisepticType">
                <el-radio v-for="dict in dictDataMap['sys_yes_no']" :key="dict.dictValue"
                          :value="dict.dictValue">{{
                    dict.dictLabel
                  }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="OTC类型">
              <el-radio-group v-model="form.isOtc">
                <el-radio v-for="dict in dictDataMap['sys_yes_no']" :key="dict.dictValue"
                          :value="dict.dictValue">{{
                    dict.dictLabel
                  }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否国采">
              <el-radio-group v-model="form.isNationalProcurement">
                <el-radio v-for="dict in dictDataMap['sys_yes_no']" :key="dict.dictValue"
                          :value="dict.dictValue">{{
                    dict.dictLabel
                  }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="GMP标识">
              <el-radio-group v-model="form.gmp">
                <el-radio v-for="dict in dictDataMap['sys_yes_no']" :key="dict.dictValue"
                          :value="dict.dictValue">{{
                    dict.dictLabel
                  }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="批准文号" prop="passNo">
              <el-input ref="passNo" v-model="form.passNo" v-keyupEnter="{ index: 0, name: 'passNo' }"
                        placeholder="请输入批准文号"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="条形码" prop="barCode">
              <el-input v-model="form.barCode" v-keyupEnter="{ index: 0, name: 'barCode' }"
                        placeholder="请输入条形码"/>
            </el-form-item>
          </el-col>
          <!--                    <el-col :span="6">-->
          <!--                        <el-form-item label="拆分系数">-->
          <!--                            <el-input ref="splitNum" v-model="form.splitNum"-->
          <!--                                      placeholder="请输入拆分系数" @keyup.enter.native="$changeFocus('channel')"/>-->
          <!--                        </el-form-item>-->
          <!--                    </el-col>-->
          <el-col :span="6">
            <el-form-item label="默认途径" prop="channel">
              <administration-index v-keyupEnter="{ index: 0, name: 'channel' }" :placeholder="'请选择途径'"
                                    :value="form.channel"
                                    @administrationInfoChange="administrationInfoChange"
                                    @changeFocusAdmin="changeFocusAdmin('performFreq')"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="默认频次" prop="performFreq">
              <perform-index ref="performIndex" v-keyupEnter="{ index: 0, name: 'performFreq' }"
                             :placeholder="'请选择频次'"
                             :value="form.performFreq"
                             @changeFocusPerformFreq="changeFocusAdmin('storageWay')"
                             @performFreqInfoChange="performFreqInfoChange"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="招采标志">
              <el-radio-group v-model="form.isPurchase">
                <el-radio v-for="dict in dictDataMap['sys_yes_no']" :key="dict.dictValue"
                          :value="dict.dictValue">{{
                    dict.dictLabel
                  }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="存储方式" prop="storageWay">
              <el-input ref="storageWay" v-model="form.storageWay" v-keyupEnter="{ index: 0, name: 'storageWay' }"
                        placeholder="请输入存储方式"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="药监本位码" prop="drugStandardCode">
              <el-input ref="drugStandardCode" v-model="form.drugStandardCode"
                        v-keyupEnter="{ index: 0, name: 'drugStandardCode' }"
                        placeholder="请输入药监本位码"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="备注信息" prop="remarks">
              <el-input v-model="form.remarks" v-keyupEnter="{ index: 0, name: 'remarks' }"
                        placeholder="请输入备注信息"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="DDD值" prop="remarks1">
              <el-input ref="remarks1" v-model="form.remarks1"
                        v-keyupEnter="{ index: 0, name: 'remarks1' }"
                        placeholder="请输入DDD值"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="备用2" prop="remarks2">
              <el-input v-model="form.remarks2" v-keyupEnter="{ index: 0, name: 'remarks2' }"
                        placeholder="请输入备用2"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="备用3" prop="remarks3">
              <el-input v-model="form.remarks3" v-keyupEnter="{ index: 0, name: 'remarks3' }"
                        placeholder="请输入备用3"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="备用4" prop="remarks4">
              <el-input v-model="form.remarks4" v-keyupEnter="{ index: 0, name: 'remarks4' }"
                        placeholder="请输入备用4"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否审核">
              <el-radio-group v-model="form.auditState">
                <el-radio v-for="dict in dictDataMap['sys_yes_no']" :key="dict.dictValue"
                          :value="dict.dictValue">{{
                    dict.dictLabel
                  }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left"><span class="divider-css">▶药品价格◀</span></el-divider>
        <el-row>
          <el-table :key="tableTime" ref="table" :border="true" :data="form.drugPriceList"
                    :header-cell-style="$headerCellStyle" :stripe="true"
                    header-cell-class-name="requiredClass"
                    highlight-current-row style="width: 100%">
            <el-table-column :align="'center'" label="药品编码" prop="drugCode">
              <template #default="scope">
                <el-form-item :prop="'drugPriceList.' + scope.$index + '.drugCode'"
                              :rules="rules.drugCode"
                              class="table-form-margin">
                  <el-input v-model="scope.row.drugCode" disabled></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="单位" prop="packageUnits" width="80px">
              <template #default="scope">
                <el-form-item class="table-form-margin">
                  <el-tag v-if="!scope.row.packageUnits">无</el-tag>
                  <dict-data-tag v-else :options="dictDataMap['spec_unit']"
                                 :value="scope.row.packageUnits"/>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="规格" prop="packageSpec">
              <template #default="scope">
                <el-form-item :prop="'drugPriceList.' + scope.$index + '.packageSpec'"
                              :rules="rules.packageSpec"
                              class="table-form-margin">
                  <el-input v-model="scope.row.packageSpec" disabled></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="进价(元)" prop="tradePrice" width="90px">
              <template #default="scope">
                <el-form-item :prop="'drugPriceList.' + scope.$index + '.tradePrice'"
                              :rules="rules.tradePrice"
                              class="table-form-margin">
                  <el-input v-model="scope.row.tradePrice"
                            v-keyupEnter="{ index: scope.$index, name: 'tradePrice' }"
                            :disabled="scope.row.packSize === '1' || form.isExistStock"
                            @blur="tradePriceBlue(scope.$index)"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="比例" prop="ratio" width="100px">
              <template #default="scope">
                <el-form-item :prop="'drugPriceList.' + scope.$index + '.ratio'"
                              class="table-form-margin">
                  <el-select ref="ratio" v-model="scope.row.ratio"
                             v-keyupEnter="{ index: scope.$index, name: 'ratio' }"
                             :disabled="scope.row.packSize === '1' || form.isExistStock"
                             filterable
                             placeholder="请选择比例" style="width: 100%"
                             @change="tradePriceBlue(scope.$index)"
                             @keyup.enter.native="$changeFocus('passNo')">
                    <el-option v-for="dict in dictDataMap['price_ratio']" :key="dict.dictValue"
                               :label="dict.dictLabel"
                               :value="dict.dictValue"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="售价(元)" prop="retailPrice" width="100px">
              <template #default="scope">
                <el-form-item :prop="'drugPriceList.' + scope.$index + '.retailPrice'"
                              :rules="rules.retailPrice"
                              class="table-form-margin">
                  <el-input v-model="scope.row.retailPrice"
                            v-keyupEnter="{ index: scope.$index, name: 'retailPrice' }"
                            :disabled="scope.row.packSize === '1' || form.isExistStock"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="门诊费用分类" prop="classOnRcpt" width="100">
              <template #default="scope">
                <el-form-item :prop="'drugPriceList.' + scope.$index + '.classOnRcpt'"
                              :rules="rules.classOnRcpt"
                              class="table-form-margin">
                  <el-select ref="ratio" v-model="scope.row.classOnRcpt"
                             v-keyupEnter="{ index: scope.$index, name: 'classOnRcpt' }"
                             filterable
                             placeholder="请选择"
                             style="width: 100%">
                    <el-option v-for="dict in dictDataMap['outp_rcpt_fee_dict']"
                               :key="dict.dictValue"
                               :label="dict.dictLabel" :value="dict.dictValue"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="住院费用分类" prop="classOnInp" width="100">
              <template #default="scope">
                <el-form-item :prop="'drugPriceList.' + scope.$index + '.classOnInp'"
                              :rules="rules.classOnInp"
                              class="table-form-margin">
                  <el-select ref="ratio" v-model="scope.row.classOnInp"
                             v-keyupEnter="{ index: scope.$index, name: 'classOnInp' }"
                             filterable placeholder="请选择"
                             style="width: 100%">
                    <el-option v-for="dict in dictDataMap['inp_rcpt_fee_dict']"
                               :key="dict.dictValue"
                               :label="dict.dictLabel" :value="dict.dictValue"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="核算项目分类" prop="classOnReckoning" width="100">
              <template #default="scope">
                <el-form-item :prop="'drugPriceList.' + scope.$index + '.classOnReckoning'"
                              :rules="rules.classOnReckoning" class="table-form-margin">
                  <el-select ref="ratio" v-model="scope.row.classOnReckoning"
                             v-keyupEnter="{ index: scope.$index, name: 'classOnReckoning' }"
                             filterable
                             placeholder="请选择" style="width: 100%"
                             @keyup.enter.native="$changeFocus('passNo')">
                    <el-option v-for="dict in dictDataMap['reck_item_class_dict']"
                               :key="dict.dictValue"
                               :label="dict.dictLabel" :value="dict.dictValue"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="会计科目" prop="subjCode" width="100">
              <template #default="scope">
                <el-form-item :prop="'drugPriceList.' + scope.$index + '.subjCode'"
                              :rules="rules.subjCode"
                              class="table-form-margin">
                  <el-select ref="ratio" v-model="scope.row.subjCode"
                             v-keyupEnter="{ index: scope.$index, name: 'subjCode' }" filterable
                             placeholder="请选择"
                             style="width: 100%">
                    <el-option v-for="dict in dictDataMap['tally_subject_dict']"
                               :key="dict.dictValue"
                               :label="dict.dictLabel" :value="dict.dictValue"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="病案首页分类" prop="classOnMr" width="100">
              <template #default="scope">
                <el-form-item :prop="'drugPriceList.' + scope.$index + '.classOnMr'"
                              :rules="rules.classOnMr"
                              class="table-form-margin">
                  <el-select ref="ratio" v-model="scope.row.classOnMr"
                             v-keyupEnter="{ index: scope.$index, name: 'classOnMr' }" filterable
                             placeholder="请选择"
                             style="width: 100%">
                    <el-option v-for="dict in dictDataMap['mr_fee_class_dict']"
                               :key="dict.dictValue"
                               :label="dict.dictLabel" :value="dict.dictValue"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="启用日期" prop="startDate" width="200">
              <template #default="scope">
                <el-form-item :prop="'drugPriceList.' + scope.$index + '.startDate'"
                              :rules="rules.startDate"
                              class="table-form-margin">
                  <el-date-picker v-model="scope.row.startDate" clearable placeholder="请选择起用日期"
                                  style="width: 100%"
                                  type="datetime" value-format="YYYY-MM-DD HH:mm:ss">
                  </el-date-picker>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" class-name="small-padding fixed-width" fixed="right" label="操作"
                             width="150">
              <template #default="scope">
                <el-button v-if="scope.row.packSize !== '1'" type="primary"
                           @click="splitBigPackageSpec(scope.row)">
                  <template #icon>
                    <i-ep-edit/>
                  </template>
                  拆分【大包装】
                </el-button>
                <el-button v-if="!form.isExistStock && scope.row.packSize === '1'"
                           type="danger" @click="deleteSmallPackageSpec(scope.$index)">
                  <template #icon>
                    <i-ep-edit/>
                  </template>
                  删除【小包装】
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </span>
      </template>
    </el-dialog>
    <drug-supplier-cata-add ref="drugSupplierCataAddRef" :supplier-class="'0'" :tabs-name="'生产商'"
                            :title="'添加药品生产商维护'"
                            @getList="setSupplierCata"/>
  </div>
</template>

<script lang="ts" setup>
import {posiNactiveNumber, positiveNumber, tradePriceV} from "@/utils/myRules";
import {addDrugInfo, getAutoDrugCode, getDrugInfo, updateDrugInfo} from "@/api/drug/drugInfo";
// import producer from "@/components/DrugSupplierCata/producer";
import {useUserStoreHook} from "@/store/modules/user";
import {useDictStoreHook} from "@/store/modules/dict";
import {firstLetterResult} from "@/utils/pinyin";
// 新增厂商组件
import drugSupplierCataAdd from "@/views/drug/drugSupplierCata/drugSupplierCataAdd.vue";

const emits = defineEmits(['getListParent'])
const useUserStore = useUserStoreHook();
const {proxy} = getCurrentInstance() as any;
const dictStore = useDictStoreHook();
const dictDataMap = ref(
  dictStore.isTypeGetData(
    "is_medical_insurance",
    "sys_yes_no",
    "drug_form_dict",
    "basic_drug_type",
    "limit_class_dict",
    "drug_toxi_property_dict",
    "drug_classification",
    "spec_unit",
    "dose_unit",
    "price_ratio",
    "tally_subject_dict",
    "outp_rcpt_fee_dict",
    "inp_rcpt_fee_dict",
    "spec_unit",
    "reck_item_class_dict",
    "mr_fee_class_dict"
  )
);
const formRef = ref();
// 是否显示弹出层
const open = ref(false);
// 按钮loading
const buttonLoading = ref(false);
const tableTime = ref(new Date().getTime());
const firmName = ref();
const drugSupplierCataAddRef = ref();
const title = ref();
const ids = ref();
const props = defineProps({
  // 药品类型List
  drugTypeOptions: {
    type: Array,
    default: () => [],
  },
  // 机构id
  orgId: {
    type: String,
    default: "",
  },
});
// 表单参数
const form = ref<any>({
  // 药品价格list
  drugPriceList: [
    {
      packSize: "2",
      ratio: "1",
      tradePrice: "",
      drugCode: "",
      packageUnits: "",
      packageSpec: "",
      retailPrice: "",
      classOnRcpt: "",
      classOnInp: "",
      classOnReckoning: "",
      subjCode: "",
      classOnMr: "",
      startDate: "",
      orgId: props.orgId,
      supplySign: "Y",
    },
  ],
});
// 表单校验
const rules = ref({
  firmId: [{required: true, message: "药品厂商不能为空", trigger: "change"}],
  toxiProperty: [{required: true, message: "毒理分类不能为空", trigger: "change"}],
  limitClass: [{required: true, message: "限制等级不能为空", trigger: "change"}],
  drugFrom: [{required: true, message: "药品剂型不能为空", trigger: "change"}],
  drugType: [{required: true, message: "药品类别不能为空", trigger: "change"}],
  drugClass: [{required: true, message: "药品分类不能为空", trigger: "change"}],
  drugClassName: [{required: true, message: "药品分类名称不能为空", trigger: "blur"}],
  drugName: [{required: true, message: "药品名称不能为空", trigger: "blur"}],
  drugInput: [{required: true, message: "药品拼音码不能为空", trigger: "blur"}],
  drugCode: [{required: true, message: "药品编码不能为空", trigger: "blur"}],
  sysDrugCode: [{required: true, message: "药品编码不能为空", trigger: "blur"}],
  spec: [{required: true, message: "规格不能为空", trigger: "blur"}],
  packageSpec: [{required: true, message: "包装规格不能为空", trigger: "blur"}],
  packageUnits: [{required: true, message: "包装单位不能为空", trigger: "change"}],
  packageUnitName: [{required: true, message: "包装单位名称不能为空", trigger: "blur"}],
  minSpec: [{required: true, message: "最小单位规格不能为空", trigger: "blur"}],
  minUnits: [{required: true, message: "最小单位不能为空", trigger: "change"}],
  minUnitsName: [{required: true, message: "最小单位名称不能为空", trigger: "blur"}],
  packageNum: [{required: true, validator: positiveNumber, trigger: "blur"}],
  splitNum: [{required: true, message: "拆分系数不能为空", trigger: "blur"}],
  dose: [
    {
      required: true,
      message: "剂量不能为空",
      validator: posiNactiveNumber,
      trigger: "blur",
    },
  ],
  doseUnits: [{required: true, message: "剂量单位不能为空", trigger: "change"}],
  doseUnitsName: [{required: true, message: "剂量单位名称不能为空", trigger: "blur"}],
  passNo: [{required: true, message: "批准文号不能为空", trigger: "change"}],
  orgId: [{required: true, message: "机构id不能为空", trigger: "blur"}],
  tradePrice: [{required: true, validator: tradePriceV, trigger: "blur"}],
  retailPrice: [{required: true, message: "不能为空", trigger: "blur"}],
  startDate: [{required: true, message: "起用日期不能为空", trigger: "blur"}],
  classOnRcpt: [{required: true, message: "不能为空", trigger: "change"}],
  classOnInp: [{required: true, message: "不能为空", trigger: "change"}],
  classOnReckoning: [
    {required: true, message: "不能为空", trigger: "change"},
  ],
  subjCode: [{required: true, message: "不能为空", trigger: "change"}],
  classOnMr: [{required: true, message: "不能为空", trigger: "change"}],
});

/** 设置生产商信息 */
function setSupplierCata(obj) {
  form.value.firmId = obj.id;
  form.value.firmName = obj.supplierName;
  firmName.value.getProducerList();
}

/** 新增厂家 */
function addSupplier() {
  drugSupplierCataAddRef.value.handleAdd();
}

/** 生产厂商点击事件 */
function producerChange(obj) {
  form.value.firmId = obj.id;
  form.value.firmName = obj.supplierName;
}

/**
 * 字典select 点击事件
 * @param value select选中值
 * @param type 字典 type
 * @param name 字典对应的属性名称
 */
function selectChange(value, type, name) {
  let dictInfo: any = {};
  if (type) {
    let dictIndex = dictDataMap.value[type].findIndex((item) => {
      return item.value || item.dictValue === value;
    });
    if (dictIndex > -1) {
      dictInfo = dictDataMap.value[type][dictIndex];
      form.value[name] = dictInfo.label || dictInfo.dictLabel;
    }
    if (type === 'drug_classification') {
      getAutoDrugCodeFun()
    }
  }
}

/**
 * 药品名称焦点消失
 */
function drugNameBlue() {
  const drugName: string = form.value.drugName;
  if (drugName) {
    // 根据药品名称获取药品别名
    form.value.drugNameAlias = drugName;
  }
  drugInputSplicing();
}


/**药品别名焦点消失 */
function drugNameAliasBlue() {
  drugInputSplicing()
}

/**
 * 通过药品名称和别名拼接拼音码
 */
function drugInputSplicing() {
  if (form.value.drugName) {
    form.value.drugInput = firstLetterResult(form.value.drugName);
  }
  if (form.value.drugNameAlias) {
    form.value.drugInput = form.value.drugInput + "," + firstLetterResult(form.value.drugNameAlias);
  }
  if (!form.value.drugName && !form.value.drugNameAlias) {
    form.value.drugInput = "";
    form.value.drugNameAlias = "";
  }
}

/** 进价焦点消失 、计算售价*/
function tradePriceBlue(index) {
  // 进价
  let tradePrice = form.value.drugPriceList[index].tradePrice;
  if (tradePrice) {
    // 获取点击行的行号index
    const ratioIndex = dictDataMap.value["price_ratio"].findIndex((item) => {
      return item.value || item.dictValue === form.value.drugPriceList[index].ratio;
    });
    if (ratioIndex > -1) {
      const dictInfo = dictDataMap.value["price_ratio"][ratioIndex];

      // 设置本行售价
      form.value.drugPriceList[index].retailPrice = (
        tradePrice * Number(dictInfo.label || dictInfo.dictLabel)
      ).toFixed(4);
    }
    // 判断是否存在小包装数据，有的话同时修改
    const smallTrIndex = form.value.drugPriceList.findIndex((item) => {
      return item.packSize === "1";
    });
    if (smallTrIndex > -1) {
      let smallTr = form.value.drugPriceList[smallTrIndex];
      smallTr.tradePrice = (tradePrice / Number(form.value.packageNum)).toFixed(4);
      smallTr.retailPrice = (
        form.value.drugPriceList[index].retailPrice / Number(form.value.packageNum)
      ).toFixed(4);
      smallTr.ratio = form.value.drugPriceList[index].ratio;
    }
  }
  tableTime.value = new Date().getTime();
}

/** 默认途径选择事件 */
function administrationInfoChange(obj) {
  form.value.channel = obj.dictValue;
}

/** 默认频次选择事件 */
function performFreqInfoChange(obj) {
  form.value.performFreq = obj.freqId;
}

function changeFocusAdmin(str) {
  proxy.$changeFocus(str);
}

/*
 * 自动计算包装单位等数据
 * @param event 选中值
 * @param type select 类别
 * @param dictType 字典类型 （设置字典翻译名称时使用）
 * @param name 字典对应name （设置字典翻译名称时使用）
 */
function chargeInput(event, type, dictType, name) {
  selectChange(event, dictType, name);
  nextTick(() => {
    // 最小规格
    let minSpec = "";
    // 最小单位名称
    let minUnitsName = "";
    //包装单位名称
    let packageUnitName = "";
    if (type === "drugCode") {
      form.value.drugPriceList[0].drugCode = form.value.drugCode;
    }
    let index = dictDataMap.value['dose_unit'].findIndex((item) => {
      return item.value || item.dictValue === form.value.doseUnits;
    });
    if (index > -1) {
      const dictInfo = dictDataMap.value['dose_unit'][index];
      const doseUnitsName = dictInfo.label || dictInfo.dictLabel;
      minSpec = proxy.$strIsUndefined(form.value.dose) + doseUnitsName
      if (type != 'minSpec') {
        form.value.minSpec = minSpec
      }
    }

    // 最小单位
    let minUnitsIndex = dictDataMap.value["spec_unit"].findIndex((item) => {
      return item.value || item.dictValue === form.value.minUnits;
    });
    if (index > -1) {
      const dictInfo = dictDataMap.value["spec_unit"][minUnitsIndex];
      minUnitsName = dictInfo.label || dictInfo.dictLabel;
    }

    // 包装单位
    let packageUnitsIndex = dictDataMap.value["spec_unit"].findIndex((item) => {
      return item.value || item.dictValue === form.value.packageUnits;
    });
    if (index > -1) {
      const dictInfo = dictDataMap.value["spec_unit"][packageUnitsIndex];
      packageUnitName = dictInfo.label || dictInfo.dictLabel;
    }
    if (type === 'lastPackageSpec') {
      form.value.drugPriceList[0].packageSpec = form.value.packageSpec
    } else {
      // 组织最终包装规格字符串
      let lastSpec = tissueLastSpecStr(form.value.minSpec, form.value.packageNum, minUnitsName, packageUnitName);

      form.value.packageSpec = lastSpec;
      form.value.drugPriceList[0].packageSpec = lastSpec;
    }
    form.value.drugPriceList[0].packageUnits = form.value.packageUnits;
    updateSmallTr();
    tableTime.value = new Date().getTime();
  });
}

/**
 * 组织最终包装规格字符串
 * @param minSpec 最小规格
 * @param packageNum 包装数量
 * @param minUnitsName 最小单位名称
 * @param packageUnitName 包装单位名称
 */
function tissueLastSpecStr(minSpec: string, packageNum: string, minUnitsName: string, packageUnitName: string) {
  return proxy.$strIsUndefined(minSpec) +
    "*" +
    proxy.$strIsUndefined(packageNum) +
    minUnitsName +
    "/" +
    packageUnitName;
}

/** 修改小规格数据 */
function updateSmallTr() {
  let index = form.value.drugPriceList.findIndex((item) => {
    return item.packSize === "1";
  });
  if (index > -1) {
    let bigTr = form.value.drugPriceList[0];
    let packageSpec = bigTr.packageSpec;
    // let specArray = packageSpec.split("*");
    form.value.drugPriceList[index].drugCode = bigTr.drugCode + "x";
    form.value.drugPriceList[index].packageUnits = form.value.minUnits;
    form.value.drugPriceList[index].packageSpec = form.value.minSpec;
  }
}

/** 拆分【大包装】 */
function splitBigPackageSpec(_obj) {
  if (!form.value.drugCode || !form.value.drugName || !form.value.packageSpec) {
    return ElMessage.error("药品信息不完整，请填写完整后再拆分");
  }
  let index = form.value.drugPriceList.findIndex((item) => {
    return item.packSize === "1";
  });
  if (index <= -1) {
    let bigTr = form.value.drugPriceList[0];
    let packageSpec = bigTr.packageSpec;
    // let specArray = packageSpec.split("*");
    let smallTr = {
      packSize: "1",
      ratio: bigTr.ratio,
      drugInfoId: bigTr.drugInfoId,
      tradePrice: (bigTr.tradePrice / Number(form.value.packageNum)).toFixed(4),
      drugCode: bigTr.drugCode + "x",
      packageUnits: form.value.minUnits,
      packageSpec: form.value.minSpec,
      retailPrice: (bigTr.retailPrice / Number(form.value.packageNum)).toFixed(4),
      classOnRcpt: bigTr.classOnRcpt,
      classOnInp: bigTr.classOnInp,
      classOnReckoning: bigTr.classOnReckoning,
      subjCode: bigTr.subjCode,
      classOnMr: bigTr.classOnMr,
      startDate: "",
      orgId: props.orgId,
      supplySign: "Y",
    };
    form.value.drugPriceList.push(smallTr);
  } else {
    return ElMessage.error("此药品已拆分，不能再次拆分");
  }
}

/** 删除【小包装】 */
function deleteSmallPackageSpec(index) {
  form.value.drugPriceList.splice(index, 1);
  //@ts-ignore
  formRef.validate();
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    drugId: undefined,
    drugType: undefined,
    drugTypeName: undefined,
    drugFrom: undefined,
    drugFromName: undefined,
    drugClass: undefined,
    drugClassName: undefined,
    drugName: undefined,
    drugInput: undefined,
    drugCode: undefined,
    drugStandardCode: undefined,
    sysDrugCode: undefined,
    toxiProperty: "A",
    toxiPropertyName: undefined,
    limitClass: "0",
    limitClassName: undefined,
    barCode: undefined,
    spec: undefined,
    packageSpec: undefined,
    packageUnits: undefined,
    packageUnitName: undefined,
    supplierId: undefined,
    supplierName: undefined,
    firmId: undefined,
    firmName: undefined,
    minSpec: undefined,
    minUnits: undefined,
    minUnitsName: undefined,
    packageNum: undefined,
    splitNum: undefined,
    dose: undefined,
    doseUnits: undefined,
    doseUnitsName: undefined,
    channel: undefined,
    performFreq: undefined,
    passNo: undefined,
    isOtc: "N",
    isNationalProcurement: "N",
    gmp: "Y",
    basicDrugType: undefined,
    antisepticType: "N",
    isPurchase: "N",
    storageWay: undefined,
    delFlag: undefined,
    orgId: props.orgId,
    createBy: undefined,
    createTime: undefined,
    updateBy: undefined,
    updateTime: undefined,
    remarks: undefined,
    remarks1: undefined,
    remarks2: undefined,
    remarks3: undefined,
    remarks4: undefined,
    auditState: "0",
    countryYbName: undefined,
    countryYbCode: undefined,
    parentId: undefined,
    platformDrugInfo: undefined,
    highRisk: "N",
    zfOrYb: "1",
  };
}

function drugTypeClick(data, _e) {
  form.value.drugType = data.classCode;
  form.value.drugTypeName = data.className;
  getAutoDrugCodeFun()
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  form.value.drugPriceList = [
    {
      packSize: "2",
      ratio: "1",
      tradePrice: "",
      drugCode: "",
      units: "",
      packageSpec: "",
      retailPrice: "",
      classOnRcpt: "",
      classOnInp: "",
      classOnReckoning: "",
      subjCode: "",
      classOnMr: "",
      startDate: "",
      orgId: props.orgId,
      supplySign: "Y",
    },
  ];
  tableTime.value = new Date().getTime();
  open.value = true;
  title.value = "添加药品字典基本信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value;
  getDrugInfo(id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改药品字典基本信息";
  });
}

/** 提交按钮 */
function submitForm() {
  (formRef.value as any).validate((valid) => {
    if (valid) {
      buttonLoading.value = true;
      debugger
      if (form.value.id != null) {
        form.value.spec = form.value.minSpec
        console.log("form.value", form.value)
        updateDrugInfo(form.value)
          .then((_response) => {
            ElMessage.success("修改成功");
            open.value = false;
            emits('getListParent')
            // getList();
          })
          .finally(() => {
            buttonLoading.value = false;
          });
      } else {
        addDrugInfo(form.value)
          .then((_response) => {
            ElMessage.success("新增成功");
            open.value = false;
            emits('getListParent')
            // getList();
          })
          .finally(() => {
            buttonLoading.value = false;
          });
      }
    }
  });
}

/***/
function drugTypeNormalizer(node) {
  if (node.children && !node.children.length) {
    delete node.children;
  }
  return {
    id: node.classCode,
    label: node.className,
    children: node.children,
  };
}

function getAutoDrugCodeFun() {
  const params = {
    orgId: props.orgId,
    drugClass: form.value.drugClass,
    drugType: form.value.drugType
  }
  getAutoDrugCode(params).then((res: any) => {
    form.value.drugCode = res.data
    form.value.drugPriceList[0].drugCode = form.value.drugCode;
  })
}

defineExpose({
  handleAdd,
  handleUpdate,
});
</script>

<script lang="ts">
export default {
  name: "drugAdd",
};
</script>

<style scoped>
:deep(.el-col) {
  margin-bottom: -2px;
}

:deep(.el-divider__text.is-left) {
  font-weight: bold;
  font-size: 19px;
}

:deep(.el-table .cell) {
  padding-left: 5px;
  padding-right: 5px;
}

:deep(.table-form-margin > div) {
  margin-left: 0 !important;
}

:deep(.el-icon-plus) {
  margin-left: -2px;
}

:deep(.firm-name-div > div) {
  margin-bottom: 0 !important;
}

:deep(.el-divider--horizontal) {
  display: block;
  height: 1px;
  width: 100%;
  margin: 14px 0 20px 0;
}

:deep(.el-form-item__content) {
  display: block;
}

</style>

<!--<style>-->
<!--.el-dialog__header {-->
<!--  padding-bottom: 0 !important;-->
<!--}-->

<!--.el-dialog__footer {-->
<!--  padding-top: 0 !important;-->
<!--}-->

<!--.el-dialog__body {-->
<!--  padding-top: 0 !important;-->
<!--}-->
<!--</style>-->
